<?php

use Core\AdminController;
use Models\Refund;
use Models\OrderRefund;
use Models\Order;

class RefundController extends AdminController
{
	public function index()
	{

		$order_refund = new OrderRefund;


		$refund = new Refund;
		$order_no = $this->input->get('order_id');
		if($order_no){
			$order = Order::or_where([
				'id' => $order_no,
				'order_id' => $order_no
			])->get_one();
			if ($order) {
				$order_refund->where('order_id', $order['id']);
			} else {
				$order_refund->where('order_id', null);
			}
		}

		$start_date = $this->input->get('start_date');
		$end_date = $this->input->get('end_date');
		$pay_mode = $this->input->get('pay_mode');
		if($start_date){
			$order_refund->where('create_time >', $start_date);
		}

		if($end_date){
			$order_refund->where('create_time <=', $end_date.'23:59:59');
		}

		if($pay_mode === '0' || $pay_mode == 1){
			$order_refund->where('pay_mode', $pay_mode);
		}

		$page = $order_refund->with([
				'user' => function ($query) {
	                $query->select('id, phone, first_name, last_name, balance');
	            },
	            'cashier' => function ($query) {
	                $query->select('id, username');
	            },
	            'order' => function ($query) {
	                $query->select('id, order_id');
	            }
			])
			->order_by('id desc')
			->paginate(20);

		return $this->load->view('admin/refund/index', [
			'page' => $page,
			'pay_types' => config('basic.pay_types')
		]);
	}

	public function detail($id)
	{
		$refund = (new Refund)->find($id);
		$refunds = Refund::where('order_refund_id', $id)
			->default_filter(false)
			->with([
				'item' => function ($q) {
					$q->select('id, product_id, title, en_title, price, tax')->with([
						'product' => function ($q) {
							$q->select('id, title, en_title');
						}
					]);
				},
				'product' => function ($q) {
					$q->select('id, title, en_title');
				}
			])->get();

		$this->load->view('admin/refund/detail', [
			'refunds' => $refunds,
		]);
	}

	public function change_status($id)
	{
		$status = $this->input->post('status');

		$refund = (new Refund)->find($id);
		$refund->update($id, [
			'status' => $status,
		]);

		return $this->response([]);
	}
}
